﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HeresyManager;

public partial class Controls_CharacterCreatorControl : System.Web.UI.UserControl
{

    public Character Character { get; private set; }

    String UID;

    private CharacterCreator Creator;

    private IEnumerator<HeresyManager.Comunication.Comunicator> Comunicator;

    protected override void LoadViewState(object savedState)
    {
        UID = savedState as String;

        Comunicator = Session[UID + "Comunicator"] as IEnumerator<HeresyManager.Comunication.Comunicator>;
        Creator = Session[UID + "Creator"] as CharacterCreator;
        if (Creator != null)
            Character = Creator.Character;
        ComunicationControl.Comunicator = Comunicator != null ? Comunicator.Current : null;
    }

    protected override object SaveViewState()
    {
        Session[UID + "Comunicator"] = Comunicator;
        Session[UID + "Creator"] = Creator;
        return UID;
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        UID = Guid.NewGuid().ToString();
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        NextButton.Enabled = ComunicationControl.Comunicator != null;

    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        ComunicationControl.Comunicator = Comunicator != null ? Comunicator.Current : null;
        if (Character != null && Creator.CharacterIsFinished)
        {
            NextButton.Text = "Save Character";
        }
        else
        {
            NextButton.Text = "Next";
            NextButton.Enabled = ComunicationControl.Comunicator != null;
        }
    }

    protected void NextButton_Click(object sender, EventArgs e)
    {
        if (Character != null && Creator.CharacterIsFinished)
        {
            
            UserData.AddCharacter(Character);
       
            Creator = null;
            ComunicationControl.Comunicator = null;
            Comunicator = null;
            Character = null;
        }
        else
        {
            if (Comunicator == null)
                return;
            if (!Comunicator.MoveNext())
            {
                if (Creator.Character == null)
                    throw new Exception("Charakter sollte hir nicht merh null sein");
                return;
            }
            ComunicationControl.Comunicator = Comunicator.Current;
        }
    }
    protected void CreateButton_Click(object sender, EventArgs e)
    {
        Creator = new CharacterCreator();
        var enumerator = Creator.CreateCharacter();
        enumerator.MoveNext();
        Comunicator = enumerator;
    }


}